import axios from "axios";
import { Dialog } from "vant";
// import { getToken } from "./auth";
const instance = axios.create({
  baseURL: 'http://localhost:3000', //请求的域名前缀
  timeout: 5000,
})

//全局请求拦截
instance.interceptors.request.use(
  function (config) {
    // if (getToken()) {
    //   // console.log(getToken())
    //   config.headers.authorization = `Bearer ${getToken()}`;
    // }
    return config;
  },
  function (error) {
    return Promise.reject(error)
  }
)

//全局响应拦截
instance.interceptors.response.use(
  function (response) {
    // console.log(response)
    return response.data
  },
  function (error) {
    // console.log(getToken())
    const { status } = error.response
    if (status === 401) {
      Dialog.confirm({
        title: '未登录',
        message: '是否前往登录',
      })
        .then(() => {
          // on confirm
          window.location.href = '#/login'
        })
        .catch(() => {
          // on cancel
        })
    }
    // if (status === 404) {
    //   window.location.href = "/personal";
    // }
    return Promise.reject(error);
  }
)

//封装get请求
export const get = (url, params) => instance.get(url, { params })
//封装post请求
export const post = (url, data) => instance.post(url, data)
//封装delete请求
export const del = (url, params) => instance.delete(url, { params })
//封装put请求
export const put = (url, params) => instance.put(url, params)

export default instance
